﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using System.Windows.Data;
using ShopOnline.Web;
using System.ComponentModel;
using System.ServiceModel.DomainServices.Client;

namespace ShopOnline.Views
{
    public partial class ViewProducts : Page
    {
        private DomainServiceShopOnline dsShopOnline;
        private PagedCollectionView products;
        private List<ProductInCart> cart;

        private const string FILTERED = "Products filtered by category - \"";

        public ViewProducts()
        {
            InitializeComponent();
            this.dsShopOnline = new DomainServiceShopOnline();
            this.dsShopOnline.PropertyChanged += dsShopOnline_PropertyChanged;
            this.cart = new List<ProductInCart>();
            CalculateTotal();
        }

        void dsShopOnline_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            this.busyIndicator.IsBusy = !this.busyIndicator.IsBusy;            
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            this.dsShopOnline.Load(this.dsShopOnline.GetProductsQuery());
            this.dsShopOnline.Load(this.dsShopOnline.GetCategoriesQuery());
            this.products = new PagedCollectionView(this.dsShopOnline.Products);
            this.comboBoxCategories.ItemsSource = this.dsShopOnline.Categories;
            this.comboBoxCategories.SelectedValuePath = "CategoryID";
            this.comboBoxCategories.DisplayMemberPath = "CategoryName";            
        }

        private void BindGridAndPager(PagedCollectionView collection, string searchMode)
        {
            if (collection.Count > 0)
            {
                ChangeVisibility(Visibility.Visible);
                this.textBlockResult.Text = searchMode;
                this.dataGridProducts.ItemsSource = collection;
                this.dataPagerProducts.Source = collection;                
            }
            else
            {
                ChangeVisibility(Visibility.Collapsed);
                this.textBlockResult.Text = searchMode + " <no results>";
            }            
        }

        private void buttonFilter_Click(object sender, RoutedEventArgs e)
        {
            var result = from product in this.dsShopOnline.Products
                         where product.CategoryID == (int)comboBoxCategories.SelectedValue
                         select product;
            this.products = new PagedCollectionView(result);
            BindGridAndPager(this.products, FILTERED +
                ((Category)comboBoxCategories.SelectedItem).CategoryName + "\"");
        }

        private void ChangeVisibility(Visibility visibility)
        {
            this.dataGridProducts.Visibility = visibility;
            this.dataPagerProducts.Visibility = visibility;            
        }

        private void buttonAddToCart_Click(object sender, RoutedEventArgs e)
        {
            Product product = (Product)this.dataGridProducts.SelectedItem;
            ProductInCart productInCart = new ProductInCart(product.ProductID, product.ProductName, 0, product.Price);
            QuantityChildWindow quantity = new QuantityChildWindow(productInCart);
            quantity.Show();
            quantity.Closed += new EventHandler(quantity_Closed);                       
        }

        void quantity_Closed(object sender, EventArgs e)
        {
            QuantityChildWindow quantity = (QuantityChildWindow)sender;
            bool alreadyInCart = false;
            if (quantity.DialogResult == true)
            {
                
                for (int i = 0; i < cart.Count; i++)
                {
                    if (cart[i].ProductID == quantity.productToAdd.ProductID)
                    {
                        cart[i].Ammount += quantity.productToAdd.Ammount;
                        alreadyInCart = true;
                    }                    
                }
                if (!alreadyInCart)
                {
                    cart.Add(quantity.productToAdd);
                }
                this.dataGridCart.ItemsSource = null;
                this.dataGridCart.ItemsSource = cart;
                CalculateTotal();
            }
        }

        private void CalculateTotal()
        {
            decimal total = 0;
            foreach (ProductInCart item in cart)
            {
                total += item.Price * item.Ammount;                
            }
            if (total == 0m)
            {
                this.buttonOrder.IsEnabled = false;
                this.buttonClear.IsEnabled = false;
            }
            else
            {
                this.buttonOrder.IsEnabled = true;
                this.buttonClear.IsEnabled = true;
            }
            this.textBoxTotal.Text = String.Format("{0:c}",total);            
        }

        private void ButtonRemove_Click(object sender, RoutedEventArgs e)
        {
            ProductInCart productToRemove = (ProductInCart)dataGridCart.SelectedItem;
            this.dataGridCart.ItemsSource = null;
            cart.Remove(productToRemove);
            this.dataGridCart.ItemsSource = cart;
            CalculateTotal();
        }

        private void buttonOrder_Click(object sender, RoutedEventArgs e)
        {
            Order newOrder = new Order();
            MakeOrderChildWindow makeOrder = new MakeOrderChildWindow(newOrder);
            makeOrder.Closed += new EventHandler(makeOrder_Closed);
            makeOrder.Show();
        }

        void makeOrder_Closed(object sender, EventArgs e)
        {
            MakeOrderChildWindow makeOrder = (MakeOrderChildWindow)sender;
            if (makeOrder.DialogResult == true)
            {
                this.dsShopOnline.Orders.Add(makeOrder.NewOrder);
                this.dsShopOnline.SubmitChanges(OrderSubmittedCallback, makeOrder.NewOrder);
            }
        }

        private void OrderSubmittedCallback(SubmitOperation op)
        {
            if (!op.HasError)
            {
                Order order = (Order)op.UserState;
                foreach (ProductInCart item in cart)
                {
                    OrderProduct orderProduct = new OrderProduct()
                    {
                        OrderID = order.OrderID,
                        ProductID = item.ProductID,
                        Quantity = item.Ammount
                    };
                    this.dsShopOnline.OrderProducts.Add(orderProduct);
                }
                MessageBox.Show("Your order number is: #" + order.OrderID + ". Write it down!",
                    "Order successful!",MessageBoxButton.OK);
            }            
            this.dsShopOnline.SubmitChanges(OrderProductSubmittedCallback, null);
        }

        private void OrderProductSubmittedCallback(SubmitOperation op)
        {
            if (op.HasError)
            {
                ErrorWindow err = new ErrorWindow("Products for order did not populated in database!",
                    "Please, inform you system administrator for this problem!");
            }
            else
            {
                cart = new List<ProductInCart>();
                this.dataGridCart.ItemsSource = null;
                this.dataGridCart.ItemsSource = cart;
                CalculateTotal();
            }
        }

        private void buttonClear_Click(object sender, RoutedEventArgs e)
        {
            cart = new List<ProductInCart>();
            this.dataGridCart.ItemsSource = null;
            this.dataGridCart.ItemsSource = cart;
            CalculateTotal();
        }
    }
}
